package com.efounder.common;

import android.content.pm.ApplicationInfo;
import android.util.Log;

import com.utilcode.util.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;

/**
 * okhttpclinet 管理
 * <p>
 * Created by YQS.
 * Date: 2019/6/27
 * Time: 11:14
 */
public class OkHttpClientManager {
    private static final String TAG = "OkHttpClientManager";
    private static volatile OkHttpClientManager instance;
    private OkHttpClient okHttpClient;
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    /**
     * 获取单例管理
     *
     * @return
     */
    public static OkHttpClientManager getInstance() {
        if (instance == null) {
            synchronized (OkHttpClientManager.class) {
                if (instance == null) {
                    instance = new OkHttpClientManager();
                }
            }
        }
        return instance;
    }

    /**
     * 获取OkHttpClient对象
     *
     * @return
     */
    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }

    /**
     * 添加拦截器
     *
     * @param interceptor 实现 {@link JInterceptor}接口
     * @return
     */
    public OkHttpClientManager addInterceptor(JInterceptor interceptor) {
        okHttpClient = getOkHttpClient().newBuilder().addInterceptor(interceptor.getInterceptor()).build();
        return this;
    }

    /**
     * 添加网络拦截器接口
     *
     * @param networkInterceptor
     * @return
     */
    public OkHttpClientManager addNetworkInterceptor(JInterceptor networkInterceptor) {
        okHttpClient = getOkHttpClient().newBuilder().addNetworkInterceptor(networkInterceptor.getInterceptor()).build();
        return this;
    }

    /**
     * 获取okhttp请求的cookie
     *
     * @return
     */
    public HashMap<String, List<Cookie>> getCookieStore() {
        return cookieStore;
    }


    /**
     * private----------------------------------------------------------------
     */
    private OkHttpClientManager() {
        okHttpClient = getDefaultClient();
    }


    private OkHttpClient getDefaultClient() {
        return new OkHttpClient().newBuilder()
                .connectTimeout(90, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(90, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(90, TimeUnit.SECONDS)//设置写入超时时间
                .cookieJar(getCookieJar())
                .addNetworkInterceptor(getDefaultLogInterceptor())
                .build();
    }

    /**
     * 获取默认日志打印拦截器
     *
     * @return
     */
    private Interceptor getDefaultLogInterceptor() {
        FilterLoggingInterceptor loggingInterceptor = new FilterLoggingInterceptor(new FilterLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
//                if (message.contains("market_ids") || message.contains("tickers")) {
//                    //market_ids太长，我在OkHttpClientManager118行给拦截了;
//                    return;
//                }
                int strLength = message.length();
                int start = 0;
                int end = 2000;
                for (int i = 0; i < 100; i++) {
                    //剩下的文本还是大于规定长度则继续重复截取并输出
                    if (strLength > end) {
                        Log.d(TAG, message.substring(start, end));
                        start = end;
                        end = end + 2000;
                    } else {
                        Log.d(TAG, message.substring(start, strLength));
                        break;
                    }
                }
            }
        });

        if (isApkInDebug()) {
            loggingInterceptor.setLevel(FilterLoggingInterceptor.Level.BODY);
        } else {
            //不是是debug 只打印基础日志
            loggingInterceptor.setLevel(FilterLoggingInterceptor.Level.BASIC);

        }
        //todo 添加不打印日志的url
        //1.不打印币看的日志
        FilterLoggingInterceptor.addNoLogUrl("https://x.szsing.com");

        return loggingInterceptor;
    }

    private CookieJar getCookieJar() {
        return new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                cookieStore.put(httpUrl.host(), list);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                List<Cookie> cookies = cookieStore.get(httpUrl.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        };
    }

    /**
     * 判断当前应用是否是debug状态
     */

    public static boolean isApkInDebug() {
        try {
            ApplicationInfo info = Utils.getApp().getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

}
